const express = require('express');
const router = express.Router();
const mysql = require('mysql2');
const multer = require('multer');
const path = require('path');
const { db } = require('../config');

// 创建数据库连接池
const pool = mysql.createPool(db);

// 配置multer用于图片上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../uploads'));
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname);
    const filename = Date.now() + ext;
    cb(null, filename);
  }
});
const upload = multer({ storage: storage });

// 获取商品列表
router.get('/', (req, res) => {
  pool.query('SELECT * FROM goods', (err, results) => {
    if (err) {
      console.error('查询商品列表出错:', err);
      return res.status(500).json({ error: '数据库查询失败', detail: err.message });
    }
    res.json({ code: 0, data: results });
  });
});

// 新增商品（支持图片上传）
router.post('/', upload.single('image'), (req, res) => {
  const { name, price, description } = req.body;
  let imageUrl = '';
  if (req.file) {
    imageUrl = `http://localhost:3000/uploads/${req.file.filename}`;
  }
  if (!name || !price || !imageUrl) {
    return res.status(400).json({ code: 1, message: '参数不完整' });
  }
  pool.query(
    'INSERT INTO goods (name, price, image, description) VALUES (?, ?, ?, ?)',
    [name, price, imageUrl, description || ''],
    (err, result) => {
      if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
      res.json({ code: 0, message: '新增成功', id: result.insertId });
    }
  );
});

// 删除商品
router.delete('/:id', (req, res) => {
  const id = req.params.id;
  pool.query('DELETE FROM goods WHERE id = ?', [id], (err, result) => {
    if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
    res.json({ code: 0, message: '删除成功' });
  });
});

// 编辑商品（支持图片可选上传）
router.put('/:id', upload.single('image'), (req, res) => {
  const id = req.params.id;
  const { name, price, description } = req.body;
  let sql = 'UPDATE goods SET name=?, price=?, description=?';
  let params = [name, price, description];
  if (req.file) {
    sql += ', image=?';
    params.push(`http://localhost:3000/uploads/${req.file.filename}`);
  }
  sql += ' WHERE id=?';
  params.push(id);
  pool.query(sql, params, (err, result) => {
    if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
    res.json({ code: 0, message: '编辑成功' });
  });
});

// 兼容小程序上传图片时编辑商品（POST方式）
router.post('/:id', upload.single('image'), (req, res) => {
  const id = req.params.id;
  const { name, price, description } = req.body;
  let sql = 'UPDATE goods SET name=?, price=?, description=?';
  let params = [name, price, description];
  if (req.file) {
    sql += ', image=?';
    params.push(`http://localhost:3000/uploads/${req.file.filename}`);
  }
  sql += ' WHERE id=?';
  params.push(id);
  pool.query(sql, params, (err, result) => {
    if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
    res.json({ code: 0, message: '编辑成功' });
  });
});

module.exports = router; 